import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/MarketApi.dart';
import 'package:flutter_2b_client/apis/MarketOrderApi.dart';
import 'package:flutter_2b_client/model/IntIdAndName.dart';
import 'package:flutter_2b_client/store/EmployeeAuthorizationStore.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_2b_client/utils/Page.dart';
import 'package:flutter_2b_client/utils/PagingUtils.dart';
import 'package:flutter_2b_client/utils/local_datetime.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:provider/provider.dart';

class MarketDetailPage extends HookWidget {
  final int id;

  const MarketDetailPage(this.id, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var marketDetailState = useState<MarketDetail?>(null);
    var pagingController =
        usePagingController<Pageable, QueryMarketOrderInMarketResponse>(
            firstPageKey: Pageable());
    useSlicingControllerListener(
        pagingController,
        (pageable) => marketOrderApi.queryMarketOrderInMarket(id, pageable),
        (item) => item.id,
        [id]);
    useEffect(() {
      marketApi.getMarketDetail(id).then((data) {
        marketDetailState.value = data;
      });

      return null;
    }, [id]);
    var me = useObservable(
        () => Provider.of<EmployeeAuthorizationStore>(context).me);
    var createOrderLoadingState = useState(false);
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            title: Text(marketDetailState.value?.name ?? "卖场详情"),
            actions: [
              PopupMenuButton(
                onSelected: (value) {
                  if (value == 0) {
                    context.push("/markets/$id/checkInventoryRecords");
                  }else if(value == 1){
                    context.push("/markets/$id/goods?marketName=${marketDetailState.value?.name}");
                  }
                },
                itemBuilder: (BuildContext context) {
                  return [
                    const PopupMenuItem(
                      value: 0,
                      child: Text("盘点"),
                    ),
                    const PopupMenuItem(
                      value: 1,
                      child: Text("商品"),
                    ),
                  ];
                },
              ),
            ],
          ),
          PagedSliverList(
            pagingController: pagingController,
            builderDelegate:
                PagedChildBuilderDelegate<QueryMarketOrderInMarketResponse>(
              itemBuilder: (BuildContext context,
                  QueryMarketOrderInMarketResponse item, int index) {
                return ListTile(
                  key: Key(item.id.toString()),
                  title: Text(item.createdDateTime.toLocalDate().format()),
                  subtitle: Text([
                    item.status.displayString,
                    "${item.goodsKindAmount}个单品"
                  ].join("\n")),
                  isThreeLine: true,
                  onTap: () async {
                    if (item.status == MarketOrderStatus.DELIVERY &&
                        me?.hasAuthority("卖场_送货单_查看") == true) {
                      context.push("/markets/$id/deliveryOrders/${item.id}");
                    } else {
                      var object = await context.push("/markets/$id/orders/${item.id}");
                      if(object is String && object=="DELETE"){
                        final list = pagingController.itemList!.toList()
                        ..remove(item);
                        if(pagingController.nextPageKey!=null){
                          list.addAll((await marketOrderApi.queryMarketOrderInMarket(id, Pageable(page: list.length-1,size: 1))).content);
                        }
                        pagingController.itemList = list;
                      }
                    }
                  },
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: me?.hasAuthority("卖场_订单_下单") == true
          ? FloatingActionButton(
              onPressed: createOrderLoadingState.value
                  ? null
                  : () async {
                      try {
                        createOrderLoadingState.value = true;
                        var orderId = await marketOrderApi.createOrder(id);
                        var queryMarketOrderInMarketResponse =
                            QueryMarketOrderInMarketResponse(
                          id: orderId,
                          createdDateTime: LocalDateTime.now(),
                          createdBy: IntIdAndName(id: me!.id, name: me.name),
                          status: MarketOrderStatus.WAIT_SUBMIT,
                          goodsKindAmount: 0,
                        );
                        pagingController.itemList = pagingController.itemList
                            ?.toList()
                          ?..add(queryMarketOrderInMarketResponse);
                        if (context.mounted) {
                          context.push("/markets/$id/orders/$orderId");
                        }
                      } finally {
                        createOrderLoadingState.value = false;
                      }
                    },
              tooltip: "下单",
              child: const Icon(Icons.add),
            )
          : null,
    );
  }
}
